<?php

namespace app\common\model;

use think\Model;


class Mycard extends Model
{

    

    

    // 表名
    protected $name = 'mycard';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_data_text',
        'status_text'
    ];
    

    
    public function getTypeDataList()
    {
        return ['0' => __('Type_data 0'), '1' => __('Type_data 1'), '2' => __('Type_data 2')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }


    public function getTypeDataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type_data']) ? $data['type_data'] : '');
        $list = $this->getTypeDataList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    protected static function init()
    {
        $log=Mycard::where("end_time< ".time())->where(["status"=>'0'])->find();
        if(!empty($log)){
            Mycard::where("end_time< ".time())->where(["status"=>'0'])->update(["status"=>'1']);
        }
            $log=Mycardlog::field("mycard_id")->where("residue >0 ")->group("mycard_id")->select();
            $log_id=[];
            if(!empty($log)){
                foreach ($log as $v){
                    $log_id[]=$v["mycard_id"];
                }
                Mycard::whereNotIn("id",$log_id)->where(["status"=>'0'])->update(["status"=>'2']);
            }
    }
    public function member()
    {
        return $this->belongsTo('Member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    /**
     * 生成二维码
     * */
    public function getCode($id,$type=1){
        if(!empty($type)){
            $mycard=$this->where(["id"=>$id])->find();
        }else{
            $mycard=Order::where(["id"=>$id])->find();
        }
        if(empty($mycard)) return false;
        /*生成二维码 start*/
        $config = get_addon_config('qrcode');
        $qrCode = \addons\qrcode\library\Service::qrcode(["text"=>"id=".$id."&type=".$type]);
        // 写入到文件
        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath  .md5("connection_id".$id). '.' . $config['format'];
            $qrCode->writeFile($filePath);
        }
        $url=cdnurl("/uploads/qrcode/".md5("connection_id".$id). '.' . $config['format']);
        /*生成二维码 end*/
        $mycard->save(["code"=>$url]);
    }
}
